// API Service - Real backend connection only (no mock data)
import { Subject, KnowledgePoint, QuizQuestion } from '../types/quiz';
import { backendApi, api as backendApiMethods } from './backendApi';

// API response interface
interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
  error?: string;
  timestamp: string;
}

// Create standard API response
const createApiResponse = <T>(data: T, success: boolean = true, message?: string, error?: string): ApiResponse<T> => ({
  success,
  data,
  message,
  error,
  timestamp: new Date().toISOString()
});

// API Service class - all methods use real backend
export class ApiService {
  // Get all subjects
  static async getSubjects(): Promise<ApiResponse<Subject[]>> {
    try {
      const response = await backendApiMethods.subjects.getAll();
      if (response.success) {
        return createApiResponse(response.data || [], true);
      }
      return createApiResponse([], false, undefined, response.error || 'Failed to fetch subjects');
    } catch (error) {
      console.error('Failed to fetch subjects:', error);
      return createApiResponse([], false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Get knowledge points by subject
  static async getKnowledgePointsBySubject(subjectId: string): Promise<ApiResponse<KnowledgePoint[]>> {
    try {
      const response = await backendApiMethods.knowledgePoints.getBySubject(subjectId);
      if (response.success) {
        return createApiResponse(response.data || [], true);
      }
      return createApiResponse([], false, undefined, response.error || 'Failed to fetch knowledge points');
    } catch (error) {
      console.error('Failed to fetch knowledge points:', error);
      return createApiResponse([], false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Get questions by knowledge points
  static async getQuestionsByKnowledgePoints(knowledgePointIds: string[]): Promise<ApiResponse<QuizQuestion[]>> {
    try {
      const response = await backendApiMethods.questions.getByKnowledgePoints(knowledgePointIds);
      if (response.success) {
        return createApiResponse(response.data || [], true);
      }
      return createApiResponse([], false, undefined, response.error || 'Failed to fetch questions');
    } catch (error) {
      console.error('Failed to fetch questions:', error);
      return createApiResponse([], false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Get knowledge point by ID
  static async getKnowledgePointById(id: string): Promise<ApiResponse<KnowledgePoint | null>> {
    try {
      // Backend doesn't have this endpoint yet, fetch all and filter
      const response = await backendApiMethods.knowledgePoints.getAll();
      if (response.success && response.data) {
        const knowledgePoint = response.data.find((kp: KnowledgePoint) => kp.id === id);
        return createApiResponse(knowledgePoint || null, true);
      }
      return createApiResponse(null, false, undefined, response.error || 'Failed to fetch knowledge point');
    } catch (error) {
      console.error('Failed to fetch knowledge point:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Match knowledge point for a quiz
  static async matchKnowledgePoint(
    quizText: string,
    targetHints?: {
      volume?: string;
      unit?: string;
      lesson?: string;
      sub?: string;
    }
  ): Promise<ApiResponse<{
    matched: KnowledgePoint | null;
    candidates: KnowledgePoint[];
    keywords: string[];
    country: string;
    dynasty: string;
  }>> {
    try {
      const response = await backendApiMethods.knowledgePoints.match(quizText, targetHints);
      if (response.success) {
        return createApiResponse(response.data || { matched: null, candidates: [], keywords: [], country: '未知', dynasty: '无' }, true);
      }
      return createApiResponse({ matched: null, candidates: [], keywords: [], country: '未知', dynasty: '无' }, false, undefined, response.error || 'Failed to match knowledge point');
    } catch (error) {
      console.error('Failed to match knowledge point:', error);
      return createApiResponse({ matched: null, candidates: [], keywords: [], country: '未知', dynasty: '无' }, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Get knowledge point hierarchy options
  static async getKnowledgePointHierarchy(filters?: {
    volume?: string;
    unit?: string;
    lesson?: string;
  }): Promise<ApiResponse<{
    volumes: string[];
    units: string[];
    lessons: string[];
    subs: string[];
  }>> {
    try {
      const response = await backendApiMethods.knowledgePoints.getHierarchyOptions(filters);
      if (response.success) {
        return createApiResponse(response.data || { volumes: [], units: [], lessons: [], subs: [] }, true);
      }
      return createApiResponse({ volumes: [], units: [], lessons: [], subs: [] }, false, undefined, response.error || 'Failed to fetch hierarchy options');
    } catch (error) {
      console.error('Failed to fetch hierarchy options:', error);
      return createApiResponse({ volumes: [], units: [], lessons: [], subs: [] }, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Get question by ID
  static async getQuestionById(id: string): Promise<ApiResponse<QuizQuestion | null>> {
    try {
      const response = await backendApiMethods.questions.getById(id);
      if (response.success) {
        return createApiResponse(response.data || null, true);
      }
      return createApiResponse(null, false, undefined, response.error || 'Failed to fetch question');
    } catch (error) {
      console.error('Failed to fetch question:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Create knowledge point
  static async createKnowledgePoint(knowledgePoint: Omit<KnowledgePoint, 'id'>): Promise<ApiResponse<KnowledgePoint>> {
    try {
      const response = await backendApiMethods.knowledgePoints.create(knowledgePoint);
      if (response.success && response.data) {
        return createApiResponse(response.data, true, 'Knowledge point created successfully');
      }
      return createApiResponse({} as KnowledgePoint, false, undefined, response.error || 'Failed to create knowledge point');
    } catch (error) {
      console.error('Failed to create knowledge point:', error);
      return createApiResponse({} as KnowledgePoint, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Create question
  static async createQuestion(question: Omit<QuizQuestion, 'id'>): Promise<ApiResponse<QuizQuestion>> {
    try {
      const response = await backendApiMethods.questions.create(question);
      if (response.success && response.data) {
        return createApiResponse(response.data, true, 'Question created successfully');
      }
      return createApiResponse({} as QuizQuestion, false, undefined, response.error || 'Failed to create question');
    } catch (error) {
      console.error('Failed to create question:', error);
      return createApiResponse({} as QuizQuestion, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Update knowledge point
  static async updateKnowledgePoint(id: string, updates: Partial<KnowledgePoint>): Promise<ApiResponse<KnowledgePoint | null>> {
    try {
      const response = await backendApiMethods.knowledgePoints.update(id, updates);
      if (response.success) {
        return createApiResponse(response.data || null, true, 'Knowledge point updated successfully');
      }
      return createApiResponse(null, false, undefined, response.error || 'Failed to update knowledge point');
    } catch (error) {
      console.error('Failed to update knowledge point:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Update question
  static async updateQuestion(id: string, updates: Partial<QuizQuestion>): Promise<ApiResponse<QuizQuestion | null>> {
    try {
      const response = await backendApiMethods.questions.update(id, updates);
      if (response.success) {
        return createApiResponse(response.data || null, true, 'Question updated successfully');
      }
      return createApiResponse(null, false, undefined, response.error || 'Failed to update question');
    } catch (error) {
      console.error('Failed to update question:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Delete knowledge point
  static async deleteKnowledgePoint(id: string): Promise<ApiResponse<boolean>> {
    try {
      const response = await backendApiMethods.knowledgePoints.delete(id);
      if (response.success) {
        return createApiResponse(true, true, 'Knowledge point deleted successfully');
      }
      return createApiResponse(false, false, undefined, response.error || 'Failed to delete knowledge point');
    } catch (error) {
      console.error('Failed to delete knowledge point:', error);
      return createApiResponse(false, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Delete question
  static async deleteQuestion(id: string): Promise<ApiResponse<boolean>> {
    try {
      const response = await backendApiMethods.questions.delete(id);
      if (response.success) {
        return createApiResponse(true, true, 'Question deleted successfully');
      }
      return createApiResponse(false, false, undefined, response.error || 'Failed to delete question');
    } catch (error) {
      console.error('Failed to delete question:', error);
      return createApiResponse(false, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Search questions
  static async searchQuestions(query: string, subjectId?: string): Promise<ApiResponse<QuizQuestion[]>> {
    try {
      const response = await backendApiMethods.questions.search(query, subjectId);
      if (response.success) {
        return createApiResponse(response.data || [], true);
      }
      return createApiResponse([], false, undefined, response.error || 'Failed to search questions');
    } catch (error) {
      console.error('Failed to search questions:', error);
      return createApiResponse([], false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Get statistics
  static async getStatistics(subjectId?: string): Promise<ApiResponse<any>> {
    try {
      // Backend doesn't have this endpoint, calculate from available data
      const kpResponse = subjectId 
        ? await backendApiMethods.knowledgePoints.getBySubject(subjectId)
        : await backendApiMethods.knowledgePoints.getAll();
      
      if (!kpResponse.success) {
        return createApiResponse(null, false, undefined, kpResponse.error || 'Failed to fetch statistics');
      }

      const knowledgePoints = kpResponse.data || [];
      const stats = {
        totalKnowledgePoints: knowledgePoints.length,
        totalQuestions: 0, // Would need to fetch all questions to count
        questionsByType: {
          'single-choice': 0,
          'multiple-choice': 0,
          'essay': 0
        },
        lastUpdated: new Date().toISOString()
      };
      
      return createApiResponse(stats, true);
    } catch (error) {
      console.error('Failed to fetch statistics:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Batch get questions - now using backend endpoint
  static async getBatchQuestions(questionIds: string[]): Promise<ApiResponse<QuizQuestion[]>> {
    try {
      if (questionIds.length === 0) {
        return createApiResponse([], true);
      }
      
      // Use the new backend endpoint for batch fetching
      const apiUrl = import.meta.env.VITE_API_BASE_URL?.endsWith('/v1')
        ? import.meta.env.VITE_API_BASE_URL
        : `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8718'}/v1`;
      const response = await fetch(`${apiUrl}/quiz/by-ids?ids=${questionIds.join(',')}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      
      const result = await response.json();
      
      if (result.success && result.data) {
        return createApiResponse(result.data, true);
      }
      
      return createApiResponse([], false, undefined, 'Failed to fetch questions');
    } catch (error) {
      console.error('Failed to batch fetch questions:', error);
      return createApiResponse([], false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Check quick options availability
  static async getQuickOptionsAvailability(): Promise<ApiResponse<any>> {
    try {
      const token = localStorage.getItem('jwt_token');
      
      if (!token) {
        return createApiResponse(null, false, undefined, 'Authentication required. Please login to use this feature.');
      }
      
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.endsWith('/v1')
        ? import.meta.env.VITE_API_BASE_URL
        : `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8718'}/v1`;
      const url = `${apiBaseUrl}/practice/quick-options-availability`;
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        const errorData = await response.json();
        return createApiResponse(null, false, undefined, errorData.message || 'Failed to get availability status');
      }

      const data = await response.json();
      return createApiResponse(data, true);
    } catch (error) {
      console.error('Error getting quick options availability:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Create quick practice session
  static async createQuickPracticeSession(questionLimit = 10): Promise<ApiResponse<any>> {
    try {
      const token = localStorage.getItem('jwt_token');
      
      if (!token) {
        return createApiResponse(null, false, undefined, 'Authentication required. Please login to use this feature.');
      }
      
      const params = new URLSearchParams();
      params.append('questionLimit', questionLimit.toString());
      
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.endsWith('/v1')
        ? import.meta.env.VITE_API_BASE_URL
        : `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8718'}/v1`;
      const url = `${apiBaseUrl}/practice/sessions/create-quick-practice?${params}`;
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        const errorData = await response.json();
        return createApiResponse(null, false, undefined, errorData.message || 'Failed to create quick practice session');
      }

      const data = await response.json();
      return createApiResponse(data, true);
    } catch (error) {
      console.error('Error creating quick practice session:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Create weak points practice session
  static async createWeakPointsSession(limit = 20): Promise<ApiResponse<any>> {
    try {
      const token = localStorage.getItem('jwt_token');
      
      if (!token) {
        return createApiResponse(null, false, undefined, 'Authentication required. Please login to use this feature.');
      }
      
      const params = new URLSearchParams();
      params.append('limit', limit.toString());
      
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.endsWith('/v1')
        ? import.meta.env.VITE_API_BASE_URL
        : `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8718'}/v1`;
      const url = `${apiBaseUrl}/practice/sessions/create-weak-points?${params}`;
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        const errorData = await response.json();
        return createApiResponse(null, false, undefined, errorData.message || 'Failed to create weak points session');
      }

      const data = await response.json();
      return createApiResponse(data, true);
    } catch (error) {
      console.error('Error creating weak points session:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // AI re-evaluate answer
  static async aiReevaluateAnswer(sessionId: string, questionId: string, userAnswer: string): Promise<ApiResponse<{
    isCorrect: boolean;
    reasoning: string;
    message?: string;
  }>> {
    try {
      const token = localStorage.getItem('jwt_token');
      
      if (!token) {
        return createApiResponse(null, false, undefined, 'Authentication required. Please login to use this feature.');
      }
      
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.endsWith('/v1')
        ? import.meta.env.VITE_API_BASE_URL
        : `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8718'}/v1`;
      const url = `${apiBaseUrl}/practice/sessions/ai-reevaluate`;
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          session_id: sessionId,
          question_id: questionId,
          user_answer: userAnswer
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        return createApiResponse(null, false, undefined, errorData.message || 'Failed to re-evaluate answer');
      }

      const data = await response.json();
      return createApiResponse(data, true);
    } catch (error) {
      console.error('Error re-evaluating answer:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Create wrong questions practice session
  static async createWrongQuestionsSession(userId?: string, sessionLimit = 5): Promise<ApiResponse<any>> {
    try {
      const token = localStorage.getItem('jwt_token');
      
      if (!token) {
        return createApiResponse(null, false, undefined, 'Authentication required. Please login to use this feature.');
      }
      
      const params = new URLSearchParams();
      params.append('sessionLimit', sessionLimit.toString());
      
      const apiUrl = import.meta.env.VITE_API_BASE_URL?.endsWith('/v1')
        ? import.meta.env.VITE_API_BASE_URL
        : `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8718'}/v1`;
      const response = await fetch(`${apiUrl}/practice/sessions/create-wrong-questions?${params}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
      });
      
      if (response.status === 401) {
        return createApiResponse(null, false, undefined, 'Authentication required. Please login to use this feature.');
      }
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      
      const result = await response.json();
      
      if (result.session && result.quizzes) {
        return createApiResponse(result, true);
      }
      
      return createApiResponse(null, false, undefined, result.message || 'Failed to create wrong questions session');
    } catch (error) {
      console.error('Failed to create wrong questions session:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // AI analysis (not implemented in backend yet)
  static async analyzeQuestionWithAI(question: string): Promise<ApiResponse<any>> {
    return createApiResponse(null, false, undefined, 'AI analysis not available in backend yet');
  }

  // Submit quiz report
  static async submitQuizReport(report: {
    quiz_id: string;
    report_type: 'display_error' | 'wrong_answer' | 'wrong_association' | 'duplicate' | 'unclear_wording' | 'other';
    reason?: string;
    user_answer?: string;
    session_id?: string;
  }): Promise<ApiResponse<any>> {
    try {
      const token = localStorage.getItem('jwt_token');
      
      if (!token) {
        return createApiResponse(null, false, undefined, 'Authentication required. Please login to use this feature.');
      }
      
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.endsWith('/v1')
        ? import.meta.env.VITE_API_BASE_URL
        : `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8718'}/v1`;
      const url = `${apiBaseUrl}/quiz/report`;
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(report)
      });

      const data = await response.json();
      
      if (!response.ok) {
        return createApiResponse(null, false, undefined, data.error?.message || 'Failed to submit report');
      }

      return createApiResponse(data.data, true, data.data?.message);
    } catch (error) {
      console.error('Error submitting quiz report:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Get user's reports
  static async getMyReports(params?: {
    status?: 'pending' | 'reviewing' | 'resolved' | 'dismissed';
    limit?: number;
    offset?: number;
  }): Promise<ApiResponse<any[]>> {
    try {
      const token = localStorage.getItem('jwt_token');
      
      if (!token) {
        return createApiResponse([], false, undefined, 'Authentication required. Please login to use this feature.');
      }
      
      const queryParams = new URLSearchParams();
      if (params?.status) queryParams.append('status', params.status);
      if (params?.limit) queryParams.append('limit', params.limit.toString());
      if (params?.offset) queryParams.append('offset', params.offset.toString());
      
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.endsWith('/v1')
        ? import.meta.env.VITE_API_BASE_URL
        : `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8718'}/v1`;
      const url = `${apiBaseUrl}/quiz/report/my-reports?${queryParams}`;
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        const errorData = await response.json();
        return createApiResponse([], false, undefined, errorData.message || 'Failed to fetch reports');
      }

      const data = await response.json();
      return createApiResponse(data.data || [], true);
    } catch (error) {
      console.error('Error fetching user reports:', error);
      return createApiResponse([], false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }

  // Update user's report
  static async updateMyReport(reportId: string, updates: {
    reason?: string;
    report_type?: 'display_error' | 'wrong_answer' | 'wrong_association' | 'duplicate' | 'unclear_wording' | 'other';
  }): Promise<ApiResponse<any>> {
    try {
      const token = localStorage.getItem('jwt_token');
      
      if (!token) {
        return createApiResponse(null, false, undefined, 'Authentication required. Please login to use this feature.');
      }
      
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.endsWith('/v1')
        ? import.meta.env.VITE_API_BASE_URL
        : `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8718'}/v1`;
      const url = `${apiBaseUrl}/quiz/report/${reportId}`;
      const response = await fetch(url, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(updates)
      });

      if (!response.ok) {
        const errorData = await response.json();
        return createApiResponse(null, false, undefined, errorData.message || 'Failed to update report');
      }

      const data = await response.json();
      return createApiResponse(data.data, true);
    } catch (error) {
      console.error('Error updating report:', error);
      return createApiResponse(null, false, undefined, error instanceof Error ? error.message : 'Network error');
    }
  }
}

// Export convenience API functions
export const api = {
  subjects: {
    getAll: () => ApiService.getSubjects()
  },
  knowledgePoints: {
    getBySubject: (subjectId: string) => ApiService.getKnowledgePointsBySubject(subjectId),
    getById: (id: string) => ApiService.getKnowledgePointById(id),
    create: (kp: Omit<KnowledgePoint, 'id'>) => ApiService.createKnowledgePoint(kp),
    update: (id: string, updates: Partial<KnowledgePoint>) => ApiService.updateKnowledgePoint(id, updates),
    delete: (id: string) => ApiService.deleteKnowledgePoint(id)
  },
  questions: {
    getByKnowledgePoints: (kpIds: string[]) => ApiService.getQuestionsByKnowledgePoints(kpIds),
    getById: (id: string) => ApiService.getQuestionById(id),
    getBatch: (ids: string[]) => ApiService.getBatchQuestions(ids),
    create: (question: Omit<QuizQuestion, 'id'>) => ApiService.createQuestion(question),
    update: (id: string, updates: Partial<QuizQuestion>) => ApiService.updateQuestion(id, updates),
    delete: (id: string) => ApiService.deleteQuestion(id),
    search: (query: string, subjectId?: string) => ApiService.searchQuestions(query, subjectId)
  },
  practice: {
    createSession: backendApiMethods.practice.createSession,
    startSession: backendApiMethods.practice.startSession,
    getSession: backendApiMethods.practice.getSession,
    submitAnswer: backendApiMethods.practice.submitAnswer,
    completeSession: backendApiMethods.practice.completeSession,
    createWrongQuestionsSession: (userId?: string, sessionLimit?: number) => ApiService.createWrongQuestionsSession(userId, sessionLimit),
    createQuickPracticeSession: (questionLimit?: number) => ApiService.createQuickPracticeSession(questionLimit),
    createWeakPointsSession: (limit?: number) => ApiService.createWeakPointsSession(limit),
    getQuickOptionsAvailability: () => ApiService.getQuickOptionsAvailability(),
    aiReevaluateAnswer: (sessionId: string, questionId: string, userAnswer: string) => ApiService.aiReevaluateAnswer(sessionId, questionId, userAnswer),
    // Resume session methods
    getIncompleteSession: backendApiMethods.practice.getIncompleteSession,
    resumeSession: backendApiMethods.practice.resumeSession,
    abandonSession: backendApiMethods.practice.abandonSession
  },
  ai: {
    analyzeQuestion: (question: string) => ApiService.analyzeQuestionWithAI(question)
  },
  stats: {
    get: (subjectId?: string) => ApiService.getStatistics(subjectId)
  },
  reports: {
    submit: (report: Parameters<typeof ApiService.submitQuizReport>[0]) => ApiService.submitQuizReport(report),
    getMyReports: (params?: Parameters<typeof ApiService.getMyReports>[0]) => ApiService.getMyReports(params),
    updateMyReport: (reportId: string, updates: Parameters<typeof ApiService.updateMyReport>[1]) => ApiService.updateMyReport(reportId, updates)
  },
  // Convenience methods for reports (to match expected API in components)
  submitQuizReport: (report: Parameters<typeof ApiService.submitQuizReport>[0]) => ApiService.submitQuizReport(report),
  getMyReports: (params?: Parameters<typeof ApiService.getMyReports>[0]) => ApiService.getMyReports(params),
  updateMyReport: (reportId: string, updates: Parameters<typeof ApiService.updateMyReport>[1]) => ApiService.updateMyReport(reportId, updates)
};

// Default export
export default ApiService;